package com.castle.releasedemo;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.castle.utils.SecretSignUtils.calcSign;

/**
 * 秘钥对签名示例 GET请求
 * @author castle
 */
public class ApiSecretSignGetDemo {


	public static void main(String[] args) throws UnsupportedEncodingException {
		//该接口需要的密钥Id
		String secretId = "KPQ9IFf9*********ZfIo2kLbv2";
		//该接口需要的密钥Key
		String secretKey = "f303bfe*9******654682d8";

		String datetime = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
		System.out.println(datetime);

		// 请求头
		Map<String, String> headers = new HashMap<>();
		headers.put("C-Date", datetime);
		//支持 application/json 与 multipart/form-data
		headers.put("Content-Type", "application/json;charset=utf-8");
		headers.put("C-Secret",secretId);

		// 查询参数 根据实际情况调整
		Map<String, String> queryParams = new HashMap<>();
		queryParams.put("参数名","参数值");


		Map<String,Object> signMap=new HashMap<>();
		signMap.putAll(queryParams);

		// 签名
		String sign = calcSign(secretId, secretKey, datetime,signMap);
		headers.put("Sign",sign);
		System.out.println(sign);

		// 接口的url地址
		StringBuilder url = new StringBuilder("***接口地址***");

		//拼接queryParam
		if(!queryParams.isEmpty()){
			url.append("?");
			for(String paramKey:queryParams.keySet()){
				url.append(paramKey+"="+queryParams.get(paramKey)+"&");
			}
		}
		//发送请求
		OkHttpClient okHttpClient = new OkHttpClient();
		Request.Builder requestBuilder=new Request.Builder().url(url.toString());
		for(String headerKey:headers.keySet()){
			requestBuilder.addHeader(headerKey,headers.get(headerKey));
		}
		Request request=requestBuilder.build();
		try {
			final Call call = okHttpClient.newCall(request);
			Response response = call.execute();
			System.out.println(response.body().string());
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


}

